package com.banmao.mall.service.admin.impl;

import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.admin.system.AddPermissionBO;
import com.banmao.mall.model.bo.admin.system.AddRoleBO;
import com.banmao.mall.model.bo.admin.system.UpdateAdminBO;
import com.banmao.mall.model.pojo.*;
import com.banmao.mall.model.vo.admin.system.*;
import com.banmao.mall.service.admin.SystemService;
import com.banmao.mall.util.ShiroMd5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    LogMapper logMapper;
    @Autowired
    StorageMapper storageMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    public AdminListVO selectAdminList(Integer page, Integer limit, String sort, String order,String username) {

        List<ItemsBean> beanList = adminMapper.selectAdminIdList((page-1)*limit,limit,sort,order,username);
        for (ItemsBean itemsBean : beanList) {
            int id = itemsBean.getId();
            Admin adminInfo = adminMapper.selectInfoByID(id);
            String roleIds = adminInfo.getRoleIds();
            String substring = roleIds.substring(1, (roleIds.length()-1));
            String[] rolesId = substring.split(",");
            List<Integer> list = new ArrayList<>();
            for (String s : rolesId) {
                list.add(Integer.parseInt(s));
            }
            itemsBean.setRoleIds(list);
        }

        Integer total = adminMapper.selectAdminTotal((page-1)*limit,limit,sort,order,username);
        AdminListVO adminListVO = new AdminListVO();
        adminListVO.setItems(beanList);
        adminListVO.setTotal(total);
        return adminListVO;
    }

    @Override
    public List<RoleVO> selectRoleIdAndName() {
        List<RoleVO> list = roleMapper.selectRoleIdAndName();
        return list;
    }

    @Override
    public AddRoleVO2 addCreate(AddAdminVO addAdminVO) {
        Admin admin = new Admin();
        admin.setUsername(addAdminVO.getUsername());

        // 王
        // md5加密
        String password = ShiroMd5Util.SysMd5(addAdminVO.getUsername(), addAdminVO.getPassword());
        admin.setPassword(password);

        admin.setAvatar(addAdminVO.getAvatar());
        admin.setAddTime(new Date());
        admin.setDeleted(false);
        admin.setUpdateTime(new Date());
        List<Integer> roleIds = addAdminVO.getRoleIds();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Integer roleId : roleIds) {
            stringBuilder.append(roleId);
            stringBuilder.append(",");
        }
        String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
        substring = substring + "]";
        admin.setRoleIds(substring);
        Integer affect = adminMapper.insert(admin);
        AddRoleVO2 addRoleVO2 = new AddRoleVO2();
        if(affect==1){
            Integer id = admin.getId();
            addRoleVO2.setId(id);
            addRoleVO2.setUsername(addAdminVO.getUsername());

            // 王
            // md5加密
            addRoleVO2.setPassword(password);

            addRoleVO2.setAddTime(admin.getAddTime());
            addRoleVO2.setUpdateTime(admin.getUpdateTime());
            addRoleVO2.setAvatar(admin.getAvatar());
            addRoleVO2.setRoleIds(roleIds);
        }
        return addRoleVO2;
    }

    @Override
    public void deleteAdminById(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        admin.setDeleted(true);
        adminMapper.updateByPrimaryKey(admin);
    }

    @Override
    public AddRoleVO2 updateAdmin(UpdateAdminBO updateAdminBO) {
        Admin admin = new Admin();
        admin.setId(updateAdminBO.getId());
        admin.setUsername(updateAdminBO.getUsername());

        // 王
        // MD5加密
        String password = ShiroMd5Util.SysMd5(updateAdminBO.getUsername(), updateAdminBO.getPassword());
        admin.setPassword(password);

        admin.setAvatar(updateAdminBO.getAvatar());
        admin.setAddTime(updateAdminBO.getAddTime());
        admin.setDeleted(false);
        admin.setUpdateTime(new Date());
        List<Integer> roleIds = updateAdminBO.getRoleIds();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Integer roleId : roleIds) {
            stringBuilder.append(roleId);
            stringBuilder.append(",");
        }
        String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
        substring = substring + "]";
        admin.setRoleIds(substring);
        Integer affect = adminMapper.updateByPrimaryKey(admin);
        AddRoleVO2 addRoleVO2 = new AddRoleVO2();
        if(affect==1){
            Integer id = admin.getId();
            addRoleVO2.setId(id);
            addRoleVO2.setUsername(updateAdminBO.getUsername());

            addRoleVO2.setPassword(password);

            addRoleVO2.setAddTime(admin.getAddTime());
            addRoleVO2.setUpdateTime(admin.getUpdateTime());
            addRoleVO2.setAvatar(admin.getAvatar());
            addRoleVO2.setRoleIds(roleIds);
        }
        return addRoleVO2;
    }

    @Override
    public LogListVO selectLogList(Integer page, Integer limit, String sort, String order, String name) {
        LogListVO logListVO = new LogListVO();
        List<Log> list = logMapper.selectLogList((page-1)*limit,limit,sort,order,name);
        Integer total = logMapper.selectLogTotal((page-1)*limit,limit,sort,order,name);
        logListVO.setItems(list);
        logListVO.setTotal(total);
        return logListVO;
    }

    @Override
    public StorageListVO selectStorageList(Integer page, Integer limit, String sort, String order, String key, String name) {
        StorageListVO storageListVO = new StorageListVO();
        List<Storage> list = storageMapper.selectStorageList((page-1)*limit,limit,sort,order,key,name);
        Integer total = storageMapper.selectStorageTotal((page-1)*limit,limit,sort,order,key,name);
        storageListVO.setItems(list);
        storageListVO.setTotal(total);
        return storageListVO;
    }

    @Override
    public void updateStorage(Storage storage) {
        storage.setDeleted(false);
        storage.setUpdateTime(new Date());
        storageMapper.updateByPrimaryKey(storage);
    }

    @Override
    public void updateStorageDeleted(Storage storage) {
        storage.setDeleted(true);
        storageMapper.updateByPrimaryKey(storage);
    }

    @Override
    public RoleListVO selectRoleList(Integer page, Integer limit, String sort, String order, String name) {
        RoleListVO roleListVO = new RoleListVO();
        List<Role> list = roleMapper.selectRoleList((page-1)*limit,limit,sort,order,name);
        Integer total = roleMapper.selectRoleTotal((page-1)*limit,limit,sort,order,name);
        roleListVO.setItems(list);
        roleListVO.setTotal(total);
        return roleListVO;
    }

    @Override
    public Role createRole(AddRoleBO addRoleBO) {
        Role role = new Role();
        role.setAddTime(new Date());
        role.setDeleted(false);
        role.setDesc(addRoleBO.getDesc());
        role.setEnabled(true);
        role.setName(addRoleBO.getName());
        role.setUpdateTime(new Date());
        int insert = roleMapper.insert(role);
        if(insert!=1){
            return null;
        }
        return role;
    }

    @Override
    public void deleteRole(Role role) {
        role.setDeleted(true);
        role.setUpdateTime(new Date());
        roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public void updateRole(Role role) {
        role.setUpdateTime(new Date());
        roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public List<String> selectPermissionByUsername(String username) {
        String roleIds = roleMapper.selectRoleIdByUsername(username);
        List<String> listFinal = new ArrayList<>();
        String substring = roleIds.substring(1, (roleIds.length()-1));
        if(substring.length()==1){
            Integer roleId = Integer.parseInt(substring);
            listFinal = permissionMapper.selectPermissionListByRoleId(roleId);
        }
        String[] rolesId = substring.split(",");
        for (String s : rolesId) {
//            list.add(Integer.parseInt(s));
            Integer roleId = Integer.parseInt(s);//permission表
            List<String> list = permissionMapper.selectPermissionListByRoleId(roleId);
            listFinal.addAll(list);
        }
        return listFinal;
    }

    @Override
    public PermissionVO selectRolePermissions(Integer roleId) {
        PermissionVO permissionVO = new PermissionVO();
        List<SystemPermissionsBean> systemPermissionsBeanList = permissionMapper.selectPermissionsList();
        for (SystemPermissionsBean systemPermissionsBean : systemPermissionsBeanList) {
            Integer sid = systemPermissionsBean.getSid();
            List<ChildrenBeanX> childrenBeanXList = permissionMapper.selectPermissionsChildrenListBySid(sid);
            for (ChildrenBeanX childrenBeanX : childrenBeanXList) {
                Integer cid = childrenBeanX.getCid();
                List<ChildrenBean> childrenBeanList = permissionMapper.selectPermissionsChildrenDetailsListByCid(cid);
                childrenBeanX.setChildren(childrenBeanList);
            }
            systemPermissionsBean.setChildren(childrenBeanXList);
        }
        permissionVO.setSystemPermissions(systemPermissionsBeanList);
        List<String> list = permissionMapper.selectPermissionListByRoleId(roleId);
        if(list!=null&&list.size()!=0){
            String s = list.get(0);
            if(s!=null&&s.equals("*")){
                list = permissionMapper.selectId();
            }
        }else{
            list = null;
        }
        permissionVO.setAssignedPermissions(list);
        return permissionVO;
    }

    @Override
    public void updateRolePermissions(AddPermissionBO addPermissionBO) {
        Integer roleId = addPermissionBO.getRoleId();
        List<String> protoList = permissionMapper.selectPermissionListByRoleId(roleId);
        for (String proto : protoList) {
            permissionMapper.updateDeletedByRoleIdAndPermission(roleId,proto,new Date());
        }
        List<String> permissions = addPermissionBO.getPermissions();
        for (String permission : permissions) {
            Permission permission1 = new Permission();
            permission1.setRoleId(roleId);
            permission1.setPermission(permission);
            permission1.setAddTime(new Date());
            permission1.setUpdateTime(new Date());
            permission1.setDeleted(false);
            String api = permissionMapper.selectApiByPermission(permission);
            permission1.setApi(api);
            permissionMapper.insert(permission1);
        }

    }
    @Override
    public void insertLog(Log log,HttpServletRequest request) {
        log.setIp(getIpAddress(request));
        log.setType(1);
        log.setAction("登陆");
        log.setStatus(true);
        log.setAddTime(new Date());
        log.setUpdateTime(new Date());
        log.setDeleted(false);
        logMapper.insert(log);
    }

    @Override
    public void insertLogOut(Log log, HttpServletRequest request) {
        log.setIp(getIpAddress(request));
        log.setType(1);
        log.setAction("退出");
        log.setStatus(true);
        log.setAddTime(new Date());
        log.setUpdateTime(new Date());
        log.setDeleted(false);
        logMapper.insert(log);
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}
